package xyz.jcat.sco.admin.oauth2.server.auth;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import xyz.jcat.common.web.Resp;
import xyz.jcat.common.web.RespCodeMsg;
import xyz.jcat.common.web.RespException;
import xyz.jcat.web.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        if(exception.getCause() instanceof RespException) {
            RespException respException = (RespException) exception.getCause();
            WebUtils.writeJson(response, respException.getResp());
        } else {
            WebUtils.writeJson(response, Resp.fail(RespCodeMsg.LOGIN_ERROR));
        }
    }
}
